package com.wing.cabinet.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.cabinet.dao.MailInfo;
import com.wing.cabinet.dao.StoresRequisitionDao;
import com.wing.cabinet.model.entity.*;
import com.wing.cabinet.model.request.StoresRequisitionForm;
import com.wing.cabinet.model.request.StoresRequisitionProductForm;
import com.wing.cabinet.model.request.TakeDeliveryForm;
import com.wing.cabinet.model.response.StoresRequisitionProductVO;
import com.wing.cabinet.model.response.StoresRequisitionVO;
import com.wing.cabinet.utils.FindDateStatusUtil;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.CodeUtil;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.RSAUtils;
import com.wing.common.utils.Result;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.response.ProductPackVO;
import com.wing.order.dao.DynamicDao;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.service.ProductDetailService;
import com.wing.setting.model.entity.SystemRuleInfo;
import com.wing.setting.service.SystemRuleInfoService;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.UserVO;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 领新申请表-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class StoresRequisitionServiceImpl extends ServiceImpl<StoresRequisitionDao, StoresRequisition> implements StoresRequisitionService {

    @Autowired
    private StoresRequisitionProductService storesRequisitionProductService;
    @Autowired
    private DynamicDao dynamicDao;
    @Autowired
    private UserClient userClient;
    @Autowired
    private StoresRequisitionProductRecordService storesRequisitionProductRecordService;
    @Autowired
    private MessageCenterService messageCenterService;
    @Autowired
    private CabinetService cabinetService;
    @Autowired
    private CellInventorySpaceService cellInventorySpaceService;

    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private JavaMailSender javaMailSender;

    @Autowired
    private SystemRuleInfoService systemRuleInfoService;

    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    @Autowired
    private AuthorityManageService authorityManageService;

    @Autowired
    private ReceiveRecordService receiveRecordService;

    @Autowired
    private ProductDetailService productDetailService;

    @Autowired
    private EnterpriseClient enterpriseClient;
    @Autowired
    private MailInfo mailInfo;

    @Override
    public int add(StoresRequisitionForm storesRequisitionForm) {

        //校验

        StoresRequisition storesRequisition =new StoresRequisition();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(StoresRequisition.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(storesRequisitionForm, storesRequisition, copyOptions);

        return baseMapper.insert(storesRequisition);
    }

    @Override
    public List<StoresRequisitionVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<StoresRequisitionVO> pageList4app(Page page, Map<String, Object> params) {
        List<StoresRequisitionVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public StoresRequisitionVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public IPage<StoresRequisitionVO> getStoresRequisitionVOPageList(StoresRequisitionVO storesRequisitionVO,StoresRequisition.CheckStatus checkStatus,
                                                                     StoresRequisition.Status status,Integer page, Integer limit) {
       IPage<StoresRequisitionVO> iPage = new Page<>(page, limit);
        QueryWrapper<StoresRequisition> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(storesRequisitionVO.getSearchContent())){
            wrapper.and(qw -> qw.like("r.code",storesRequisitionVO.getSearchContent()).or()
                    .like("r.cabinet_code",storesRequisitionVO.getSearchContent()).or().like("wo.code",storesRequisitionVO.getSearchContent()));
            //wrapper.last(" WHERE 1=1 and CONCAT(r.code,c.code,wo.code) LIKE CONCAT ('%',"+ storesRequisitionVO.getSearchContent() +",'%')");
        }
        if(StringUtils.isNotBlank(storesRequisitionVO.getCode())){
            wrapper.like("r.code",storesRequisitionVO.getCode());
        }
        if(StringUtils.isNotBlank(storesRequisitionVO.getCabinetCode())){
            wrapper.like("r.cabinet_code",storesRequisitionVO.getCabinetCode());
        }
        if(StringUtils.isNotBlank(storesRequisitionVO.getWorkOrderCode())){
            wrapper.like("wo.code",storesRequisitionVO.getWorkOrderCode());
        }
        if(StringUtils.isNotBlank(storesRequisitionVO.getStartCreateTime())){
            wrapper.gt("r.create_time", storesRequisitionVO.getStartCreateTime());
        }
        if(StringUtils.isNotBlank(storesRequisitionVO.getEndCreateTime())){
            wrapper.le("r.create_time", storesRequisitionVO.getEndCreateTime());
        }
       if(status!=null){
           wrapper.eq("r.status", status.getValue());
       }
       if(checkStatus != null){
           wrapper.eq("r.check_status", checkStatus.getValue());
       }
       if(storesRequisitionVO.getUserId() != null){
           wrapper.eq("r.user_id", storesRequisitionVO.getUserId());
       }
       if(storesRequisitionVO.getBusinessId() != null){
           wrapper.eq("r.id", storesRequisitionVO.getBusinessId());
       }
        wrapper.eq("r.enterprise_code",JwtUtils.getEnterpriseCode());
        wrapper.orderByDesc("r.create_time");
        baseMapper.getStoresRequisitionVOPageList(iPage, wrapper);
        for (StoresRequisitionVO item : iPage.getRecords()){
            if(item.getUserId() != null){
                JsonResult<UserVO> result = userClient.getUserInfoByUserId(item.getUserId());
                if(null != result && result.getData() != null) {
                    item.setPhone(result.getData().getPhone())
                            .setDepartmentName(result.getData().getDepartmentName())
                            .setRoleName(result.getData().getRoleName());
                }
            }

        }
        return iPage;
    }

    @Transactional
    @Override
    public void submitStoresRequisitionForm(StoresRequisitionForm storesRequisitionForm) {
        StringBuffer quantitySb = new StringBuffer();
        StringBuffer oldSpecCodeSb = new StringBuffer();
        StringBuffer productNameSb = new StringBuffer();
        Integer quantity = 0;
        StoresRequisition storesRequisition =new StoresRequisition();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(StoresRequisition.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(storesRequisitionForm, storesRequisition, copyOptions);
        String enterpriseCode = storesRequisitionForm.getEnterpriseCode();
        String loginUsername = storesRequisitionForm.getCreatorName();
        Long userId = storesRequisitionForm.getUserId();
        Long loginUserId = storesRequisitionForm.getLoginUserId();
        if(StringUtils.isBlank(enterpriseCode)){
            enterpriseCode = JwtUtils.getEnterpriseCode();
        }
        storesRequisition.setEnterpriseCode(enterpriseCode);
        if(StringUtils.isBlank(loginUsername)){
            loginUsername = JwtUtils.getLoginUsername();
        }
        storesRequisition.setCreatorName(loginUsername);
        storesRequisition.setLnstructionCode((int)((Math.random()*9+1)*100000));
        String today = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        Integer maxCode = dynamicDao.getDayMaxNo("ord_stores_requisition");
        String code = CodeUtil.getCode(maxCode);
        if(userId == null){
            userId = JwtUtils.getLoginUserId();
        }
        if(loginUserId == null){
            loginUserId = JwtUtils.getLoginUserId();
        }
        storesRequisition.setUserId(userId);
        storesRequisition.setCode("LD" + today + code);
        storesRequisition.setNo(Integer.valueOf(code));
        //Cabinet cabinet = cabinetService.getCabinetVOByCabCode(storesRequisitionForm.getCabinetCode());
        storesRequisition.setCabinetCode(storesRequisitionForm.getCabinetCode());
        storesRequisition.setDay(Integer.valueOf(today));
        storesRequisition.setUuid(DigestUtil.md5Hex(UUID.randomUUID().toString()));
        storesRequisition.setUuidReject(DigestUtil.md5Hex(UUID.randomUUID().toString()));
        baseMapper.insert(storesRequisition);
        if(CollectionUtils.isNotEmpty(storesRequisitionForm.getProductDetail())){
            for (StoresRequisitionProductForm item : storesRequisitionForm.getProductDetail()){
                ProductDetail productDetail = productDetailService.getOne(new LambdaQueryWrapper<ProductDetail>().eq(ProductDetail::getSkuCode, item.getSkuCode()));
                StoresRequisitionProduct requisitionProduct = new StoresRequisitionProduct();
                requisitionProduct.setStoresRequisitionId(storesRequisition.getId())
                        .setSkuCode(item.getSkuCode())
                        .setShipmentQuantity(item.getShipmentQuantity())
                        .setRemark(item.getRemark())
                        .setPackId(item.getPackId())
//                        .setEnterpriseCode(JwtUtils.getEnterpriseCode());
                        .setEnterpriseCode(enterpriseCode);
                JsonResult<ProductPackVO> packVOJsonResult = enterpriseClient.getProductPackById(item.getPackId());
                if(packVOJsonResult.getCode()== Result.Code.SUCCESS.getCode()){
                    if(packVOJsonResult.getData().getBaseRate() != null){
                        requisitionProduct.setQuantityPack(packVOJsonResult.getData().getBaseRate() * item.getShipmentQuantity());
                        requisitionProduct.setPackName(packVOJsonResult.getData().getName());
                        requisitionProduct.setUnitName(productDetail.getUnitName());
                        requisitionProduct.setQuantityPackUnit(packVOJsonResult.getData().getBaseRate());
                    }
                }
                quantitySb.append(item.getShipmentQuantity()).append(",");
                oldSpecCodeSb.append(productDetail.getOldSpecCode()).append(",");
                productNameSb.append(productDetail.getSkuName()).append(",");
                quantity += item.getShipmentQuantity();
                storesRequisitionProductService.save(requisitionProduct);
            }
        }
        MessageCenter messageCenter = new MessageCenter();
        messageCenter.setBusinessId(storesRequisition.getId());
        messageCenter.setNewsType(MessageCenter.NewsType.takedelivery);
        messageCenterService.save(messageCenter);
        quantitySb.deleteCharAt(quantitySb.length()-1);
        oldSpecCodeSb.deleteCharAt(oldSpecCodeSb.length()-1);
        productNameSb.deleteCharAt(productNameSb.length()-1);
        // 发送邮箱
//        sendMail(quantitySb.toString(),JwtUtils.getLoginUsername(),storesRequisitionForm.getCabinetCode(),storesRequisition.getUuid()
//                ,storesRequisition.getUuidReject(),JwtUtils.getLoginUserId(),oldSpecCodeSb.toString(),productNameSb.toString(),quantity);
        sendMail(quantitySb.toString(),loginUsername,storesRequisitionForm.getCabinetCode(),storesRequisition.getUuid()
                ,storesRequisition.getUuidReject(),loginUserId,oldSpecCodeSb.toString(),productNameSb.toString(),quantity);
    }

    public void sendMail(String quantity,String applyName,String cabinetCode,String uuid,String uuidReject
            ,Long userId,String oldSpecCode,String productName,Integer shipmentQuantity) {
        executorService.submit(() -> {
            try {
                emailWithPreview(quantity,applyName,cabinetCode,uuid,uuidReject,userId,oldSpecCode,productName,shipmentQuantity);
            } catch (Exception e) {
                log.error("sendMail fail=>{}",e);
            }
        });
    }



    @Transactional
    @Override
    public void submitGetRequisitionProduct(TakeDeliveryForm takeDeliveryForm) {

        StoresRequisition storesRequisition = baseMapper.selectById(takeDeliveryForm.getStoresRequisitionId());
        if (storesRequisition == null) {
            throw new BusinessException("领新申请数据异常");
        }
        if (!storesRequisition.getLnstructionCode().equals(takeDeliveryForm.getInstructionCode())) {
            throw new BusinessException("领货密码错误，请重新输入！");
        }

    }

    @Override
    public StoresRequisitionVO getWorkOrderInfo(Long storesRequisitionId) {
        StoresRequisitionVO requisitionVO = baseMapper.get4appById(storesRequisitionId);
        //查询领取人
        if(requisitionVO.getUserId() != null){
            JsonResult<UserVO> result = userClient.getUserInfoByUserId(requisitionVO.getUserId());
            requisitionVO.setNickname(result.getData().getNickname());
        }
        //根据领新申请单的主柜编号查询售刀副柜
        List<Cabinet> cabinetVOList = cabinetService.list(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getBelongCabinet, requisitionVO.getCabinetCode())
                .eq(Cabinet::getCabinetNature,1));
        //当前领新申请单的产品
        List<StoresRequisitionProductVO> list = storesRequisitionProductService.getStoresRequisitionProductVOInfo(storesRequisitionId);
        for (StoresRequisitionProductVO productItem : list){
            for (Cabinet cabinetItem : cabinetVOList){
                List<CellInventorySpace> inventorySpaceList = cellInventorySpaceService.list(new LambdaQueryWrapper<CellInventorySpace>()
                        .eq(CellInventorySpace::getSkuCode, productItem.getSkuCode())
                        .eq(CellInventorySpace::getCabCode,cabinetItem.getCode()));
                productItem.setInventorySpaceList(inventorySpaceList);
            }
        }
        requisitionVO.setProductList(list);
        return requisitionVO;
    }
    @Transactional
    @Override
    public void requisitionProductRecord(Long storesRequisitionId, List<StoresRequisitionProductForm> productList) {
        StoresRequisition storesRequisition = baseMapper.selectById(storesRequisitionId);
        if(storesRequisition == null){
            throw new BusinessException("领新申请数据异常");
        }
        if(CollectionUtils.isEmpty(productList)){
            throw new BusinessException("领新产品参数异常");
        }
        for (StoresRequisitionProductForm item : productList){

            log.info("密码领货:item.getId()={}",item.getId());
            StoresRequisitionProduct requisitionProduct = storesRequisitionProductService.getById(item.getId());
            log.info("密码领货:requisitionProduct={}",requisitionProduct);            //查询领新产品的领取记录总数
            Integer neckQuantitySum = storesRequisitionProductRecordService.getProductNeckQuantitySum(item.getId(), requisitionProduct.getSkuCode());
            //当前领新的数量
            Integer currentQuantity =  item.getNeckQuantity() * item.getQuantityPackUnit();
            if( currentQuantity > requisitionProduct.getQuantityPack()){
                throw new BusinessException(requisitionProduct.getSkuCode() + "的领取数量不能大于出货数量！");
            }
            //领取数量不能大于剩余出货数量
            if(currentQuantity > requisitionProduct.getQuantityPack() - neckQuantitySum){
                throw new BusinessException(requisitionProduct.getSkuCode() + "的领取数量不能大于剩余出货数量！");
            }
            StoresRequisitionProductRecord record = new StoresRequisitionProductRecord();
            record.setRequisitionProductId(requisitionProduct.getId());
            record.setNeckQuantity(item.getNeckQuantity());
            record.setSkuCode(requisitionProduct.getSkuCode());
            record.setPackId(item.getPackId());
            record.setQuantityPackUnit(item.getQuantityPackUnit());
            record.setQuantityPack(item.getQuantityPack());
            record.setPackName(item.getPackName());
            record.setUnitName(item.getUnitName());
            storesRequisitionProductRecordService.save(record);
            //修改领新产品状态
            Integer neckQuantitySumRecord = storesRequisitionProductRecordService.getProductNeckQuantitySum(item.getId(), requisitionProduct.getSkuCode());
            if(neckQuantitySumRecord == requisitionProduct.getShipmentQuantity()){
                requisitionProduct.setStatus(StoresRequisitionProduct.Status.finish);
            }else{
                requisitionProduct.setStatus(StoresRequisitionProduct.Status.portion);
            }
            storesRequisitionProductService.updateById(requisitionProduct);
        }
        //修改领新申请状态
        QueryWrapper<StoresRequisitionProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("stores_requisition_id",storesRequisition.getId());
        int countAll = storesRequisitionProductService.count(wrapper);
        QueryWrapper<StoresRequisitionProduct> finishWrapper = new QueryWrapper<>();
        finishWrapper.eq("stores_requisition_id",storesRequisition.getId());
        finishWrapper.eq("status",2);
        int finishCount = storesRequisitionProductService.count(finishWrapper);
        if(finishCount == countAll){
            storesRequisition.setStatus(StoresRequisition.Status.broughtout);
        }else{
            storesRequisition.setStatus(StoresRequisition.Status.portion);
        }
        baseMapper.updateById(storesRequisition);
    }

    public void emailWithPreview(String quantity,String applyName,String cabinetCode,String uuid,String uuidReject,Long userId
            ,String oldSpecCode,String productName,Integer shipmentQuantity) {
        //领新数量
        Integer receivedQuantity = 0;
        //领新申请数量
        Integer receivedApplyQuantity = 0;
        //查询主柜
        Cabinet cabinet = cabinetService.getOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getCabCode, cabinetCode));
        //查询权限组
        AuthorityManage authorityManage = authorityManageService.getOne(new LambdaQueryWrapper<AuthorityManage>().eq(AuthorityManage::getCabinetId, cabinet.getId()));
        if(authorityManage!=null) {
            Map<String, Object> params = new HashMap<>();
            //授信方式
            if (authorityManage.getCreditWay().name().equals("share") || authorityManage.getCreditWay().name().equals("shareQuantity")) { //组员共享
                //评估周期
                if (authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                    String todayTime = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now());
                    //当前时间
                    params.put("todayTime", todayTime);
                    receivedQuantity = receiveRecordService.sumByTotalQuantity(authorityManage.getId(), todayTime);
                } else if (authorityManage.getLineEvaluatePeriod().name().equals("week")) {//每周
                    params.put("startTime", FindDateStatusUtil.getWeekStart(new Date()));
                    params.put("endTime", FindDateStatusUtil.getWeekEndTime());
                    receivedQuantity = receiveRecordService.sumQuantity(authorityManage.getId(), FindDateStatusUtil.getWeekStart(new Date()), FindDateStatusUtil.getWeekEndTime());
                } else if (authorityManage.getLineEvaluatePeriod().name().equals("month")) {//每月
                    params.put("startTime", FindDateStatusUtil.getMonthStartTime());
                    params.put("endTime", FindDateStatusUtil.getMonthEndTime());
                    receivedQuantity = receiveRecordService.sumQuantity(authorityManage.getId(), FindDateStatusUtil.getMonthStartTime(), FindDateStatusUtil.getMonthEndTime());
                } else if (authorityManage.getLineEvaluatePeriod().name().equals("quarter")) {//每季度
                    params.put("startTime", FindDateStatusUtil.getQuarterStartTime(new Date()));
                    params.put("endTime", FindDateStatusUtil.getQuarterEndTime(new Date()));
                    receivedQuantity = receiveRecordService.sumQuantity(authorityManage.getId(), FindDateStatusUtil.getQuarterStartTime(new Date()), FindDateStatusUtil.getQuarterEndTime(new Date()));
                } else if (authorityManage.getLineEvaluatePeriod().name().equals("year")) {//每年
                    params.put("startTime", FindDateStatusUtil.getYearStartTime());
                    params.put("endTime", FindDateStatusUtil.getYearEndTime());
                    receivedQuantity = receiveRecordService.sumQuantity(authorityManage.getId(), FindDateStatusUtil.getYearStartTime(), FindDateStatusUtil.getYearEndTime());
                }
                receivedApplyQuantity = storesRequisitionProductRecordService.sumReceivedApplyByTotalQuantity(params);
            } else if (authorityManage.getCreditWay().name().equals("independent") || authorityManage.getCreditWay().name().equals("independentQuantity")) {//组员独立
                params.put("userId", userId);
                params.put("authorityManageId", authorityManage.getId());
                //评估周期
                if (authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                    //当前时间
                    String todayTime = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now());
                    params.put("todayTime", todayTime);
                    receivedQuantity = receiveRecordService.sumIndependentByTotalQuantity(authorityManage.getId(), userId, todayTime);
                } else if (authorityManage.getLineEvaluatePeriod().name().equals("week")) {//每周
                    params.put("startTime", FindDateStatusUtil.getWeekStart(new Date()));
                    params.put("endTime", FindDateStatusUtil.getWeekEndTime());
                    receivedQuantity = receiveRecordService.sumIndependentQuantityByReceiverId(params);
                } else if (authorityManage.getLineEvaluatePeriod().name().equals("month")) {//每月
                    params.put("startTime", FindDateStatusUtil.getMonthStartTime());
                    params.put("endTime", FindDateStatusUtil.getMonthEndTime());
                    receivedQuantity = receiveRecordService.sumIndependentQuantityByReceiverId(params);
                } else if (authorityManage.getLineEvaluatePeriod().name().equals("quarter")) {//每季度
                    params.put("startTime", FindDateStatusUtil.getQuarterStartTime(new Date()));
                    params.put("endTime", FindDateStatusUtil.getQuarterEndTime(new Date()));
                    receivedQuantity = receiveRecordService.sumIndependentQuantityByReceiverId(params);
                } else if (authorityManage.getLineEvaluatePeriod().name().equals("year")) {//每年
                    params.put("endTime", FindDateStatusUtil.getYearEndTime());
                    params.put("startTime", FindDateStatusUtil.getYearStartTime());
                    receivedQuantity = receiveRecordService.sumIndependentQuantityByReceiverId(params);
                }
                receivedApplyQuantity = storesRequisitionProductRecordService.sumReceivedApplyByTotalQuantity(params);
            }
            Integer sumQuantity = receivedQuantity+receivedApplyQuantity+shipmentQuantity;
            // 领新审核管理员
            List<SystemRuleInfo> list = systemRuleInfoService.list();
            try {
                if (CollectionUtil.isNotEmpty(list)) {
                    if (StringUtils.isNotBlank(list.get(0).getMailManagementUserId())) {
                        String[] strId = list.get(0).getMailManagementUserId().split(",");
                        for (String item : strId) {
                            JsonResult<UserVO> userInfo = userClient.getUserInfo(Long.valueOf(item));
                            if (StringUtils.isNotBlank(userInfo.getData().getEmail())) {
                                String rsaData = RSAUtils.encryptByPublicKey(RSAUtils.publicKey, uuid);
                                String rsaData4Reject = RSAUtils.encryptByPublicKey(RSAUtils.publicKey, uuidReject);
                                InetAddress address = InetAddress.getLocalHost();
                                MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                                mimeMessage.setFrom(new InternetAddress(mailInfo.queryInfo().get("send_account").toString()));
                                mimeMessage.addRecipient(Message.RecipientType.TO,
                                        new InternetAddress(userInfo.getData().getEmail()));
                                mimeMessage.setSubject("主题：领新申请审核");
                                StringBuffer content = new StringBuffer();
                                content.append("<div style='font-size: 18px;min-height: 180px;height: auto;min-height:350px;background-color: #f5f5f7;box-shadow: 0 0 10px 3px #0000001a;border-radius: 20px;box-sizing: border-box;padding:30px;margin: 20px;'>");
                                content.append("<p>" + applyName + "发起领新申请：</p>");
                                content.append("<div style='text-align: left;min-height: 180px; margin: 10px 0;height: auto; padding-left: 2em;'>");
                                content.append("<p>物料名称为"+productName+"。</p>");
                                content.append("<p>规格为"+oldSpecCode+"。</p>");
                                content.append("<p>申请数量为"+quantity+"。</p>");
                                content.append("<p>总数量为"+sumQuantity+"（其中领新数量为"+receivedQuantity+"，领新申请数量为"+receivedApplyQuantity+"）。</p>");
                                content.append("<p>主柜位置在"+cabinet.getWorkshopLocation()+"。</p>");
                                content.append("</div>");
                                content.append("<div style='text-align:right'>");
                                content.append("<a style='background-color: #409eff; padding: 8px 12px; display: inline-block; border-radius: 10px;text-decoration: none; color: #fff; margin: 0 10px;' " +
                                        "href=http://" + address.getHostAddress() + ":9300/enterprisecab/cabinet/admin/storesRequisition/audit?signData=" + rsaData + ">审核通过</a>");
                                content.append("<a style='background-color: #f56c6c; padding: 8px 12px; display: inline-block; border-radius: 10px;text-decoration: none; color: #fff; margin: 0 10px;' " +
                                        "href=http://" + address.getHostAddress() + ":9300/enterprisecab/cabinet/admin/storesRequisition/reject?signData=" + rsaData4Reject + ">审核驳回</a>");
                                content.append("</div>");
                                content.append("</div>");
                                mimeMessage.setContent( content.toString(), "text/html;charset=UTF-8");
                                javaMailSender.send(mimeMessage);
                            }
                        }
                    }
                }
            } catch (MessagingException | UnknownHostException e) {
                log.error("发送邮件失败:" + e.getMessage());
            } catch (Exception e) {
                log.error("send mail fail", e);
            }
        }
    }


    public JsonResult<String> sendTest(String mailTo){
        try {
            InetAddress address = InetAddress.getLocalHost();
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            mimeMessage.setFrom(new InternetAddress(mailInfo.queryInfo().get("send_account").toString()));
            mimeMessage.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(mailTo));
            mimeMessage.setSubject("主题：领新申请审核");

            mimeMessage.setContent( "test", "text/html;charset=UTF-8");
            javaMailSender.send(mimeMessage);
            return JsonResult.success("success");
        } catch (MessagingException | UnknownHostException e) {
            log.error("发送邮件失败:" + e.getMessage());
            return JsonResult.fail("fail");
        } catch (Exception e) {
            log.error("send mail fail", e);
            return JsonResult.fail("fail");
        }
    }



}
